package cn.sdormitory.canteen.service.impl;

import cn.sdormitory.canteen.dao.FoodHealthCartDao;
import cn.sdormitory.canteen.service.FoodHealthCartService;
import cn.sdormitory.canteen.vo.FoodHealthCartVO;
import cn.sdormitory.canteen.vo.FoodSupplierVO;
import cn.sdormitory.common.utils.ImageToTextAIUtils;
import cn.sdormitory.common.utils.RedisUtils;
import cn.sdormitory.common.utils.SysUserUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Slf4j
@Service
public class FoodHealthCartServiceImpl extends ServiceImpl<FoodHealthCartDao, FoodHealthCartVO> implements FoodHealthCartService {

    @Autowired
    private FoodHealthCartDao foodHealthCartDao;

    @Value("${file.upload.path}")
    private String fileFolder;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public IPage<FoodHealthCartVO> getPage(Map<String, Object> params) {
        int pageSize = Integer.parseInt(String.valueOf(params.get("pageSize")));
        int pageNum = Integer.parseInt(String.valueOf(params.get("pageNum")));
        Object holderName = params.get("holderName");

        LambdaQueryWrapper<FoodHealthCartVO> wrapper = new LambdaQueryWrapper<>();

        if (!StringUtils.isEmpty(holderName)) {
            wrapper.likeRight(FoodHealthCartVO::getHolderName, holderName);
        }
        return page(new Page<>(pageNum, pageSize), wrapper);
    }

    @Override
    public int saveOrUpdateFoodHealthCart(FoodHealthCartVO vo) {
        int num=0;
        String currBy = SysUserUtils.getSysUser().getUsername();
        Date currDate = new Date();
        if(StringUtils.isEmpty(vo.getId())){
            vo.setCreateBy(currBy);
            vo.setCreatedTime(currDate);
            num = foodHealthCartDao.insert(vo);
        }else{
            vo.setModifyBy(currBy);
            vo.setModifyTime(currDate);
            num = foodHealthCartDao.updateById(vo);
        }
        return num;
    }

    @Override
    public int deleteHealthCartById(Long id) {
        return foodHealthCartDao.deleteById(id);
    }

    @Override
    public Map<String, String> autoRecognitionHealthCartPhoto(String fileName) {
        String filePath = fileFolder + fileName;
        String token = redisUtils.get("bd_image_auth_token");
        if(StringUtils.isEmpty(token)){
            token = ImageToTextAIUtils.getAuth();
            redisUtils.set("bd_image_auth_token",token,1800);
        }
        String result = ImageToTextAIUtils.getImageDoc(token,filePath);
        JSONObject json = JSON.parseObject(result);
        List<Map<String,String>> words = (List<Map<String, String>>)json.get("words_result");
        log.info("autoRecognitionHealthCartPhoto result:{}",result);
        return getCartinfo(words);
    }

    private Map<String,String> getCartinfo( List<Map<String,String>> words){
        Map<String,String> resultMap = new HashMap<>();
        for(int i=0;i<words.size();i++){
            String word = words.get(i).get("words");
            if(word.indexOf("编号")>=0){
                resultMap.put("healthCartNo",words.get(i+1).get("words"));
            }
            if(word.indexOf("姓名")>=0){
                resultMap.put("holderName",words.get(i+1).get("words"));
            }
            if(word.indexOf("年龄")>=0){
                resultMap.put("holderAge",getAge(words,i));
            }
            if(word.indexOf("体检")>=0){
                if (word.indexOf("合格") >= 0) {
                    resultMap.put("physicalExamStatus", "1");
                } else {
                    resultMap.put("physicalExamStatus", "0");
                }
            }
            if(word.indexOf("卫培")>=0){
                if (word.indexOf("及格") >= 0) {
                    resultMap.put("healthTrainedStatus", "1");
                } else {
                    resultMap.put("healthTrainedStatus", "0");
                }
            }
            if(word.indexOf("发证时间")>=0){
                String beginDate = getCertDate(words,i);
                resultMap.put("issuedCartDate", beginDate);
                resultMap.put("validTerm", getValidTerm(beginDate));
            }
            if(word.indexOf("性别")>=0){
                resultMap.put("holderSex",getSex(words,i));
            }
        }
        return resultMap;
    }

    private String getSex(List<Map<String,String>> words,int index){
        String word = words.get(index).get("words");
        String str = word.replace("性别","");
        if(StringUtils.isEmpty(str)){
            return words.get(index+1).get("words");
        }
        if("男".equals(str)) return "1";
        if("女".equals(str)) return "2";
        return str;
    }

    private String getValidTerm(String dateStr) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try{
            Calendar c = Calendar.getInstance();
            Date date = sdf.parse(dateStr);
            c.setTime(date);
            c.add(Calendar.YEAR, 1);
            Date validDate = c.getTime();
            return sdf.format(validDate);
        }catch(Exception e){
            log.error(e.getMessage());
        }

        return dateStr;
    }

    private String getCertDate(List<Map<String,String>> words,int index){
        String word = words.get(index+1).get("words");
        String[] nums = word.split("\\.");
        StringBuffer formatDateStr=new StringBuffer();
        for(int i=0;i<nums.length;i++){
            String str = nums[i];
            String flag = "";
            if(i==0&&str.length()<4){
                flag = "20"+str;
                formatDateStr.append(flag).append("-");
            }
            if(i==0&&str.length()==4){
                formatDateStr.append(str).append("-");
            }
            if(i!=0&&str.length()<2){
                flag = "0"+str;
                formatDateStr.append(flag).append("-");
            }
        }
        return formatDateStr.toString().substring(0,formatDateStr.toString().length()-1);
    }

    /**
     * 获取年龄
     * @param words
     * @param index
     * @return
     */
    private String getAge(List<Map<String,String>> words,int index){
        String word = words.get(index).get("words");
        String numStr = word.substring(word.indexOf("年龄")+2);
        boolean isNumStr = numStr.matches("[0-9]+");
        if(isNumStr) return numStr;
        return words.get(index+1).get("words");
    }

    public static void main(String[] args) {
        String dateStr = "2021.9.1";
        String[] nums = dateStr.split("\\.");

        StringBuffer formatDateStr=new StringBuffer();
        for(int i=0;i<nums.length;i++){
            String str = nums[i];
            String flag = "";
            if(i==0&&str.length()<4){
                flag = "20"+str;
                formatDateStr.append(flag).append("-");
            }
            if(i==0&&str.length()==4){
                formatDateStr.append(str).append("-");
            }
            if(i!=0&&str.length()<2){
                flag = "0"+str;
                formatDateStr.append(flag).append("-");
            }
        }
        String fs = formatDateStr.toString();

    }
}
